import { useRef, useEffect, useState, useMemo } from 'react';
import debugMan from '../lib/debugMan';
import useTableType from './useTableType';
import calcTableScroll from './lib/calcTableScroll';

const noop = () => { };
const DEFAULT_SCROLL_HEIGHT = 300;
export default function (headerFix, containerRef, rest = {}) {
    const { height, width, prefixCls } = rest;
    const tableState = useRef({ hasSizeObserver: false, headerFix });
    const resizeChangeFnRef = useRef({ tableWrapperObserverCallback: noop });
    const [tableGap, setTableGap] = useState(height || DEFAULT_SCROLL_HEIGHT);// * table中内容的可见高度
    const responsive = useTableType({ headerFix, width, height });
    // * 定义/更新tableWrapper的大小观察函数
    useEffect(() => {
        resizeChangeFnRef.current.tableWrapperObserverCallback = (entries) => {
            debugMan.console('Observe table container size modify');
            for (const entry of entries) {
                // * entry.target是tableWrapper的element
                calcTableScroll(entry.target, prefixCls, (r) => {
                    if (r.scrollAble) setTableGap(r.value);
                })
            }
        }
    }, [prefixCls])


    // * 观察table相关容器的大小的变化   
    useEffect(() => {
        // * Observer的函数只需要创建一次
        if (headerFix && responsive?.y && tableState.current.hasSizeObserver === false) {
            const resizeObserver = new ResizeObserver(resizeChangeFnRef.current.tableWrapperObserverCallback);
            resizeObserver.observe(containerRef.current);
            tableState.current.hasSizeObserver = true;            
        }
    }, [responsive, headerFix]);

    return useMemo(() => {
        return { x: width, y: headerFix ? tableGap : undefined };
    }, [headerFix, tableGap])
}





